import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

import '../../services/screen_adapter.dart';
import '../../config/config.dart';
import '../../services/user_service.dart';
import '../../services/sign_service.dart';
import '../../services/event_bus.dart';


class AddressListPage extends StatefulWidget {
  AddressListPage({Key key}) : super(key: key);

  @override
  _AddressListPageState createState() => _AddressListPageState();
}

class _AddressListPageState extends State<AddressListPage> {

  List _addressList = [];
  var _addressSubscription;

  @override
  void initState() { 
    super.initState();
    _getAddressList();
    
    /// 监听增加收货地址的广播
    _addressSubscription = eventBus.on<AddressEvent>().listen((event) {
      _getAddressList();
    });
  }

  /// 页面销毁的时候进行事件广播
  @override
  void dispose() {
    super.dispose();
    eventBus.fire(new CheckOutEvent('设置默认地址成功...'));
    _addressSubscription.cancel();
  }

  /// 获取收货地址列表
  _getAddressList() async{
    List userinfo = await UserService.getUserInfo();
    var tempJson = {
      'uid': userinfo[0]['_id'],
      'salt': userinfo[0]['salt']
    };
    var sign = SignService.getSign(tempJson);
    var api = '${Config.domain}api/addressList?uid=${userinfo[0]['_id']}&sign=$sign';
    var result = await Dio().get(api);
    if (result.data['success']) {
      setState(() {
        _addressList = result.data['result'];
      });
    }

  }

  /// 修改默认收货地址
  _changeDefaultAddress(id) async{
    List userinfo = await UserService.getUserInfo();
    var tempJson = {
      'uid': userinfo[0]['_id'],
      'id': id,
      'salt': userinfo[0]['salt']
    };
    var sign = SignService.getSign(tempJson);
    var api = '${Config.domain}api/changeDefaultAddress';
    var result = await Dio().post(api, data: {
      'uid': userinfo[0]['_id'],
      'id': id,
      'sign': sign
    });
    if (result.data['success']) {
      Navigator.pop(context);
    }
    
  }

  /// 弹出框
  _showDelAlertDialog(id) async{
    var result = await showDialog(
      context: context,
      barrierDismissible: false, //表示点击灰色背景的时候是否消失弹出框
      builder: (context) {
        return AlertDialog(
          title: Text('提示信息'),
          content: Text('您确定要删除吗?'),
          actions: <Widget>[
            FlatButton(
              onPressed: () {
                Navigator.pop(context);
              }, 
              child: Text('取消')
            ),
            FlatButton(
              onPressed: () async {
                /// 执行删除操作
                List userinfo = await UserService.getUserInfo();
                /// salt用户注册的时候服务器随机生成的私钥
                var tempJson = {
                  'id': id,
                  'uid': userinfo[0]['_id'],
                  'salt': userinfo[0]['salt']
                };

                var sign = SignService.getSign(tempJson);
                // print(sign);

                var api = '${Config.domain}api/deleteAddress';
                var result = await Dio().post(api, data:{
                  'id': id,
                  'uid': userinfo[0]['_id'],
                  'sign': sign
                });

                /// 删除收货地址完成后重新获取列表
                _getAddressList();

                Navigator.pop(context);
              }, 
              child: Text('确定')
            )
          ],
        );
      }
    );
    print(result);
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init();
    return Scaffold(
      appBar: AppBar(
        title: Text('收货地址列表')
      ),
      body: Container(
        child: Stack(
          children: <Widget>[
            SizedBox(height: 20),
            ListView.builder(
              itemCount: _addressList.length,
              itemBuilder: (context, index) {
                if(_addressList[index]['default_address'] == 1) {
                  return Column(
                    children: <Widget>[
                      ListTile(
                        leading: Icon(Icons.check, color: Colors.red),
                        title: InkWell(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text('${_addressList[index]['name']} ${_addressList[index]['phone']}'),
                              SizedBox(height: 10),
                              Text('${_addressList[index]['address']}')
                            ]
                          ),
                          onTap: () {
                            _changeDefaultAddress(_addressList[index]['_id']);
                          },
                          onLongPress: () => _showDelAlertDialog(_addressList[index]['_id'])
                        ),
                        trailing: IconButton(
                          icon: Icon(Icons.edit, color: Colors.blue), 
                          onPressed: () {
                            Navigator.pushNamed(context, '/addressEdit', arguments: {
                              'id': _addressList[index]['_id'],
                              'name': _addressList[index]['name'],
                              'phone': _addressList[index]['phone'],
                              'address': _addressList[index]['address'],
                            });
                          }
                        )
                      ),
                      Divider(height: 20),
                    ]
                  );
                } else {
                  return Column(
                    children: <Widget>[
                      ListTile(
                        title: InkWell(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text('${_addressList[index]['name']} ${_addressList[index]['phone']}'),
                              SizedBox(height: 10),
                              Text('${_addressList[index]['address']}')
                            ]
                          ),
                          onTap: () {
                            _changeDefaultAddress(_addressList[index]['_id']);
                          },
                          onLongPress: () => _showDelAlertDialog(_addressList[index]['_id'])
                        ),
                        trailing: IconButton(
                          icon: Icon(Icons.edit, color: Colors.blue), 
                          onPressed: () {
                            Navigator.pushNamed(context, '/addressEdit', arguments: {
                              'id': _addressList[index]['_id'],
                              'name': _addressList[index]['name'],
                              'phone': _addressList[index]['phone'],
                              'address': _addressList[index]['address'],
                            });
                          }
                        )
                      ),
                      Divider(height: 20),
                    ]
                  );
                }
                
              },
            ),
            Positioned(
              bottom: 0,
              width: ScreenAdapter.width(750),
              height: ScreenAdapter.height(88),
              child: Container(
                padding: EdgeInsets.all(5),
                width: ScreenAdapter.width(750),
                height: ScreenAdapter.height(88),
                decoration: BoxDecoration(
                  color: Colors.red,
                  border: Border(
                    top: BorderSide(
                      width: 1,
                      color: Colors.black26
                    )
                  )
                ),
                child: InkWell(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(Icons.add, color: Colors.white),
                      Text('增加收货地址', style: TextStyle(
                        color: Colors.white
                      ))
                    ]
                  ),
                  onTap: (){
                    Navigator.pushNamed(context, '/addressAdd');
                  },
                )
              )
            )
          ]
        )
      )
    );
  }
}